<template>
  <div style="font-size: 14px;">
    <div class="topSearch">
      <div class="tSLeft">粉丝关注7日</div>
      <div class="tSRight">
        <el-select v-model="publicNumberName" placeholder="请选择公众号" style="margin-right: 10px;">
          <el-option v-for="(item, index) in publicArr" :label="item.name" :value="item.accountId" :key="index"></el-option>
        </el-select>
        <el-radio-group v-model="dataType">
          <el-radio-button label='0'>显示百分比</el-radio-button>
          <el-radio-button label='1'>显示关注数</el-radio-button>
        </el-radio-group>
        <el-date-picker
          v-model="followTime"
          type="date"
          placeholder="选择日期"
          style="margin-left: 10px;"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
        <el-button @click="search" type="primary" style="margin-left: 10px;">查询</el-button>
      </div>
    </div>
    <el-row :gutter="20" style="margin: 20px;max-width: 1500px;min-width: 1000px;">
      <el-col :span="7" style="padding: 0;border-left: 1px solid #f5f5f5;border-right: 1px solid #f5f5f5;">
        <div class="sevenKeepP">
          <div class="title">{{liuCun}}</div>
          <div>{{followTime?`${followTime.split('-')[1]}月${followTime.split('-')[2]}日`:``}}关注的分析在一周后的留存率</div>
        </div>
        <div class="sevenContent">
          <p>图表根据筛选的日期，统计了该日新增粉丝在之后的一周内的每日留存人数（即未关注人数），并据此计算了对应的粉丝留存率，数据统计自粉丝的关注/取关时间，与粉丝趋势数据有差异。</p>
          <p>此数据自公众号授权后开始统计，授权前的留存率数据默认为100%。</p>
          <P>对于公众号来说，关注留存最主要的指标是2天留存和7天留存，留存比率越高，说明粉丝是您的目标受众的可能性越高，质量相对也更好。</P>
          <P>平均留存率用来结算某天的平均留存情况。</P>
          <P>某天平均留存率=某天留存粉丝总数/当日关注粉丝总数，如3天留存的平均留存率=3天留存的总粉丝数/前5行当日关注粉丝总和。</P>
        </div>
      </el-col>
      <el-col :span="17">
        <table>
          <thead>
            <tr>
              <th></th>
              <th>当日关注粉丝</th>
              <th>当天留存</th>
              <th>1天留存</th>
              <th>2天留存</th>
              <th>3天留存</th>
              <th>4天留存</th>
              <th>5天留存</th>
              <th>6天留存</th>
              <th>7天留存</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in tableData" :key="index" style="text-align: center;">
              <td>{{ item.date }}</td>
              <td><el-tag v-if="item.focusNum">{{ item.focusNum }}</el-tag></td>
              <td><el-tag v-if="item.day0 !== null">{{ item.day0 }}</el-tag></td>
              <td><el-tag v-if="item.day1 !== null">{{ item.day1 }}</el-tag></td>
              <td><el-tag v-if="item.day2 !== null">{{ item.day2 }}</el-tag></td>
              <td><el-tag v-if="item.day3 !== null">{{ item.day3 }}</el-tag></td>
              <td><el-tag v-if="item.day4 !== null">{{ item.day4 }}</el-tag></td>
              <td><el-tag v-if="item.day5 !== null">{{ item.day5 }}</el-tag></td>
              <td><el-tag v-if="item.day6 !== null">{{ item.day6 }}</el-tag></td>
              <td><el-tag v-if="item.day7 !== null">{{ item.day7 }}</el-tag></td>
            </tr>
          </tbody>
        </table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  /* eslint-disable */
  import service from '../../../service/count';
  import CONSTANT from '../../../constant/common';
  // 中间的数据
  export default {
    data() {
      return {
        followTime: '',
        tableData: [],
        publicNumberName: '',
        publicArr: [],
        dataType: '0',
        mergeCoundInt: [],
        mergeRatInt: [],
        mergeTime: [],
        liuCun: '',
        listLoading: true,
      };
    },
    computed: {
      publicAccountNickname() {
        const localWoa = localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA) ?
          JSON.parse(localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA)) : {};
        return this.$store.state.woa.currentWoa.publicAccountNickname || localWoa.publicAccountNickname;
      }
    },
    mounted() {
      this.getAuthorizerInfo();
      // 初始化参数s
      let newDate = new Date();
      newDate.setDate(newDate.getDate()-8);
      this.followTime = `${newDate.getFullYear()}-${(newDate.getMonth()+1)<10?"0"+(newDate.getMonth()+1):newDate.getMonth()+1}-${newDate.getDate()<10?"0"+newDate.getDate():newDate.getDate()}`;
      // 初始化参数e
    },
    methods: {
      search() {
        this.dataInit(this.dataType, { accountId: this.publicNumberName, fromTime: this.followTime});
      },
      dataInit(flag, params) {
        const that = this
        service.getRetentionCount(params).then((res) => {
          that.mergeCoundInt = res
          service.getDaySubscribe(params).then((res1) => {
            that.mergeTime = res1
            service.getRetentionRateInfo(params).then((res2) => {
              that.mergeRatInt = res2
              // 重组二维数组s

              // 填补中间没有的数据，如断层
              let subscribeCountIndex = 0;
              let subscribeRatIndex = 0;
              let countInt = [];
              let ratInt = [];
              for(let i=0;i<8;i++){
                if (that.mergeCoundInt[subscribeCountIndex] && that.timeChange(that.mergeCoundInt[subscribeCountIndex].statDate) === that.changeDate(i)) {
                  countInt.push(that.mergeCoundInt[subscribeCountIndex]);
                  subscribeCountIndex++;
                } else {
                  countInt.push({a:null,b:null,c:null,d:null,e:null,f:null,g:null,h:null});
                }

                if (that.mergeRatInt[subscribeRatIndex] && that.timeChange(that.mergeRatInt[subscribeRatIndex].statDate) === that.changeDate(i)) {
                  ratInt.push(that.mergeRatInt[subscribeRatIndex]);
                  subscribeRatIndex++;
                } else {
                  ratInt.push({a:null,b:null,c:null,d:null,e:null,f:null,g:null,h:null});
                }
              }
              let newTwoArr = [];
              let countArr = [];
              countInt.map((item) => {
                delete item.id
                delete item.statDate
                delete item.publicAccountId
                delete item.createdTime
                delete item.updateTime
                countArr.push(Object.values(item))
              })
              ratInt.map((item) => {
                delete item.id
                delete item.statDate
                delete item.publicAccountId
                delete item.createdTime
                delete item.updateTime
                newTwoArr.push(Object.values(item))
              })
              that.liuCun = newTwoArr[0]?newTwoArr[0][7]?newTwoArr[0][7]:'暂无':'暂无';
              if(flag==='1') {
                newTwoArr = countArr
              }
              // 重组二维数组e

              // 计算平均留存率s
              let dayGuan = [], subscribeUserIndex = 0;
              for(let i=0;i<8;i++) {
                if (that.mergeTime[subscribeUserIndex] && that.timeChange(that.mergeTime[subscribeUserIndex].statDate) === that.changeDate(i)) {
                  dayGuan.push(that.mergeTime[subscribeUserIndex].subscribe_user);
                  subscribeUserIndex++;
                } else {
                  dayGuan.push(0);
                }
              }
              let avgLiu = [];
              console.log(that.twoArrChange(countArr))
              that.twoArrChange(countArr).map(item => {
                let allCount = 0;
                item.arrindex.map(item=> {
                  allCount += dayGuan[item]
                })
                avgLiu.push(eval(item.arritem.join('+'))>=0?((eval(item.arritem.join('+'))/allCount)*100).toFixed(1)+'%':null)
              })
              // 计算平均留存率e

              that.tableData = [];
              for(let i=0;i<9;i++){
                let thisObj = {};
                if(i<8) {
                  // 左侧时间
                  thisObj.date = that.changeDate(i);
                  // 当日关注粉丝数
                  thisObj.focusNum = dayGuan[i];
                  for(let j=0;j<8;j++){
                    // 中间的二维数组
                    thisObj['day'+j] = newTwoArr[i]!==undefined?newTwoArr[i][j]!==undefined?newTwoArr[i][j]:null:null;
                  }
                } else {
                  thisObj.date = '';
                  thisObj.focusNum = '平均留存率';
                  for(let z=0;z<8;z++){
                    thisObj['day'+z] = avgLiu[z]
                  }
                }
                that.tableData.push(thisObj)
              }
            })
          })
        })
      },
      getAuthorizerInfo() {
        service.getAuthorizerInfo().then((res) => {
          this.publicArr = res;
          this.publicNumberName = (res.filter( item => item.name === this.publicAccountNickname ))[0].accountId;
          this.search()
        });
      },
      changeDate(num) {
        let newDate = new Date(this.followTime);
        newDate.setDate(new Date(this.followTime).getDate()+num);
        return `${(newDate.getMonth()+1)<10?"0"+(newDate.getMonth()+1):newDate.getMonth()+1}-${newDate.getDate()<10?"0"+newDate.getDate():newDate.getDate()}`;
      },
      // 二维数组转置
      twoArrChange(arr) {
        console.log(arr, 111)
        let index = 0;
        let twoArrChange = [];
        while(index<8){
          let nowArr = [];
          let arrindex = [];
          arr.map((item, index1) => {
            if(item[index]!==null){
              nowArr.push(item[index]);
              arrindex.push(index1);
            }
          })
          twoArrChange.push({arritem: nowArr, arrindex: arrindex});
          index++;
        }
        return twoArrChange;
      },
      // 时间转换格式方法
      timeChange(time) {
        return `${time.split('-')[1]}-${time.split('-')[2]}`
      },
    },
  };
</script>

<style scoped>
  .topSearch{
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #efefef;
    padding-bottom: 10px;
  }
  .tSRight{
    display: flex;
  }
  .el-table td, .el-table th.is-leaf {
    border-bottom: none!important;
  }
  table{
    width: 100%;
    min-width: 900px;
  }
  table tr{
    height: 40px;
  }
  th{
    width: 10%;
  }
  .el-tag{
    width: 80px;
  }
  .title{
    margin-bottom: 10px;
    font-size: 16px;
  }
  .sevenKeepP{
    text-align: center;
    background: #f5f5f5;
    padding: 20px 0;
  }
  .sevenContent{
    padding: 10px 20px;
  }
</style>
